// +----------------------------------------------------------------------
// | Project:   Android-Commons  
// +----------------------------------------------------------------------
// | CreateTime: 15/12/14  下午3:41
// +----------------------------------------------------------------------
// | Author:     xab(xab@xabad.cn)
// +----------------------------------------------------------------------
// | Description:
// +----------------------------------------------------------------------
package cn.xabad.commons.converter;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import retrofit.Callback;
import retrofit.HttpException;
import retrofit.Response;
import retrofit.Retrofit;

/**
 * DESC   :
 * AUTHOR : Xabad
 */
public abstract class BaseCallback<T> implements Callback<T> {

    @Override
    public void onResponse(Response<T> response, Retrofit retrofit) {
        if (response != null && response.isSuccess()) {
            onSuccess(response);
        } else {
            onFailure(null);
        }
    }


    @Override
    public void onFailure(Throwable e) {
        RetrofitError error = new RetrofitError(); if (e == null) {
            error.setCode(RetrofitError.ERROR_NULL);
        } else if (e instanceof UnknownHostException) {
            error.setCode(RetrofitError.ERROR_CONNECTION); error.setMessage(e.getMessage());
        } else if (e instanceof SocketTimeoutException) {
            error.setCode(RetrofitError.ERROR_TIMEOUT); error.setMessage(e.getMessage());
        } else if (e instanceof HttpException) {
            HttpException exception = (HttpException) e; error.setCode(exception.code());
            error.setMessage(exception.getMessage());
        } else {
            e.printStackTrace(); error.setCode(RetrofitError.ERROR_UNKNOW);
            error.setMessage(e.getMessage());
        } onFail(error);
    }


    public abstract void onFail(RetrofitError error);

    public abstract void onSuccess(Response<T> response);
}
